# -*- coding: utf-8 -*-

"""
@Datetime: 2019/1/1
@Author: Zhang Yafei
"""
from flask import Blueprint, request, url_for
from common.utils.pagination import Pagination
from Kingadmin.file_reader import reader
from common.libs.helper import ops_render


route_backend = Blueprint('backend_page', __name__, static_folder='static')


@route_backend.route('/home')
def home():
    return ops_render('home.html')


@route_backend.route('/file_list')
def file_list():
    data_list = reader.enable_admins
    page_obj = Pagination(data_list.__len__(), request.args.get('p'))
    page_str = page_obj.page_str(base_url=url_for('backend_page.file_list'))
    data_list = [{k:data_list[k]} for k in data_list.keys()][page_obj.start:page_obj.end]
    data_list = {list(item.keys())[0]: list(item.values())[0] for item in data_list}
    context = {
        'data_list': data_list,
        'page_str': page_str,
        'page_obj': page_obj,
    }
    return ops_render('file_list.html', context)


@route_backend.route('/data_list/<table_name>')
def data_list(table_name):
    admin_class = reader.enable_admins[table_name]
    page_obj = Pagination(admin_class.data.shape[0], request.args.get('p'))
    page_str = page_obj.page_str(base_url=url_for('backend_page.data_list', table_name=table_name))
    data_list = admin_class.data[page_obj.start:page_obj.end]
    context = {'table_name':table_name, 'data_list':data_list,
               'page_obj':page_obj, 'page_str':page_str,
               'admin_class':admin_class,
               }
    return ops_render('data_list.html', context)


@route_backend.route('/detail/<table_name>_<int:index>')
def detail(table_name,index):
    data = reader.enable_admins[table_name].data.loc[index]
    context = {
        'data':data,
        'table_name':table_name,
    }
    return ops_render('detail.html', context)